<?php

namespace app\company\controller;

use app\company\validate\PickingLineValidate;
use app\mini\model\StoreOrderDetail;
use app\service\traits\Crud;
use app\company\model\PickingLine as PickingLineModel;
use app\company\model\Store;
use app\company\model\StoreOrder;

class PickingLine extends Base
{
    private PickingLineModel $model;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new PickingLineModel();
        $this->validateClass = PickingLineValidate::class;
        $this->isGs          = true;
        $this->withSearch    = 'id,name,create_time';
        $this->append        = 'is_dow_text,is_print_text';
    }

    public function format($list): mixed
    {
        return $list->each(function ($item) {
            $item->dow_time   = setDates($item->dow_time);
            $item->print_time = setDates($item->print_time);
            $item->pick_time  = setDates($item->pick_time);
        });
    }


    public function detailFormat($info): mixed
    {
        $info->line         = $info->deliverLine()->field('id,no,name')->find();
        $info->company_name = $info->company()->value('name');
        $info->company_logo = $info->company()->value('logo');
        //得到所属门店
        $store = Store::where('deliver_line_id', $info->deliver_line_id)->field('id,name,address')->select()->toArray();
        $time  = date("Y-m-d", strtotime('-1 day', $info->pick_time));
        foreach ($store as $key => $item) {
            if (!$orderIds = StoreOrder::storeId($item['id'])->whereIn('order_status',[3,4])->whereDay('create_time', $time)->column('id')) {
                unset($store[$key]);
                continue;
            };
            $field                  = "goods_id,store_user_id,goods_rule_id,sum(quantity) quantity";
            $store[$key]['details'] = StoreOrderDetail::whereIn('store_order_id', $orderIds)->field($field)->group('goods_rule_id')->select()->each(function ($detail) {
                $detail->goods      = $detail->goods()->withTrashed()->field('name,no')->find();
                $detail->goods_rule = $detail->goodsRule()->withTrashed()->value('spec_name');
            });
        }
        $info->store      = array_values($store);
        $info->pick_time  = setDates($info->pick_time);
        $info->dow_time   = setDates($info->dow_time);
        $info->print_time = setDates($info->print_time);
        return $info;
    }

}